package alipay

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/wosylf/ltool"
)

func (a *Client) F创建商家券(ctx context.Context, bm ltool.BodyMap) (aliRsp *CouponSyncRsp, err error) {
	var bs []byte
	if bs, err = a.doAliPay(ctx, bm, "alipay.marketing.activity.ordervoucher.create"); err != nil {
		return nil, err
	}

	//plug.Println("alir11e1111", string(bs))
	aliRsp = new(CouponSyncRsp)
	if err = json.Unmarshal(bs, aliRsp); err != nil {
		return nil, err
	}
	if aliRsp.Response != nil && aliRsp.Response.Code != "10000" {
		//plug.Printf("alir11es%+v", aliRsp.Response)
		info := aliRsp.Response
		return aliRsp, fmt.Errorf(`{"code":"%s","msg":"%s","sub_code":"%s","sub_msg":"%s"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
	}
	signData, signDataErr := a.getSignData(bs, aliRsp.AlipayCertSn)
	aliRsp.SignData = signData
	//plug.Println("aliRsp.Response == nil {", aliRsp.Response)
	if aliRsp.Response == nil {
		res := new(CouponSync)
		if err = json.Unmarshal([]byte(signData), res); err != nil {
			return nil, err
		}
		//plug.Printf("alir11es%+v", res)
		if res.Code != "10000" {
			return aliRsp, fmt.Errorf(`{"code":"%s","msg":"%s","sub_code":"%s","sub_msg":"%s"}`, res.Code, res.Msg, res.SubCode, res.SubMsg)
		}
		aliRsp.Response = res
	}
	return aliRsp, a.autoVerifySignByCert(aliRsp.Sign, signData, signDataErr)
}

func (a *Client) F同步商家券券码(ctx context.Context, bm ltool.BodyMap) (aliRsp *CouponUploadRsp, err error) {
	var bs []byte
	if bs, err = a.doAliPay(ctx, bm, "alipay.marketing.activity.ordervoucher.codedeposit"); err != nil {
		return nil, err
	}
	//plug.Println("F同步商家券券码", string(bs))
	aliRsp = new(CouponUploadRsp)
	if err = json.Unmarshal(bs, aliRsp); err != nil {
		return nil, err
	}
	if aliRsp.Response != nil && aliRsp.Response.Code != "10000" {
		info := aliRsp.Response
		return aliRsp, fmt.Errorf(`{"code":"%s","msg":"%s","sub_code":"%s","sub_msg":"%s"}`, info.Code, info.Msg, info.SubCode, info.SubMsg)
	}
	signData, signDataErr := a.getSignData(bs, aliRsp.AlipayCertSn)
	aliRsp.SignData = signData
	return aliRsp, a.autoVerifySignByCert(aliRsp.Sign, signData, signDataErr)
}
